package cc.sunni.rabbitmq.service.impl;

import cc.sunni.rabbitmq.config.Constants;
import cc.sunni.rabbitmq.dao.MqMessageDao;
import cc.sunni.rabbitmq.dao.OrderDao;
import cc.sunni.rabbitmq.entity.MqMessage;
import cc.sunni.rabbitmq.entity.Order;
import cc.sunni.rabbitmq.producer.OrderSender;
import cc.sunni.rabbitmq.service.OrderService;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements OrderService {
    @Autowired
    private MqMessageDao mqMessageDao;
    @Autowired
    private OrderSender orderSender;

    @Override
    @Transactional
    public void createOrder(Order order) {
        // insert order 业务数据入库
        this.save(order);
        // insert mq_message 构建消息日志记录对象
        MqMessage mqMessage = new MqMessage();
        mqMessage.setMessageId(order.getMessageId());
        // save order message sa json
        mqMessage.setMessage(JSONUtil.toJsonStr(order));
        mqMessage.setStatus(Constants.MESSAGE_SENDING);
        mqMessage.setNextRetry(DateUtil.offsetMinute(new DateTime(), Constants.MESSAGE_MAX_TIMEOUT));
        mqMessageDao.insert(mqMessage);

        // order message send
        orderSender.sendOrder(order);
    }
}